package com.mmall.controller;

import com.alibaba.fastjson.JSON;
import com.mmall.service.IUserService;
import entity.JwtUtil;
import entity.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pojo.User;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@CrossOrigin  //微服务项目中涉及跨域请求
public class UserController {
    @Autowired
    private IUserService iUserService;

    @GetMapping("/{id}")
    public String getUser(@PathVariable String id) {
        return iUserService.findById(id);
    }

    @RequestMapping(value = "/login")
    public ServerResponse login(String username, String password, HttpServletResponse resp){
        ServerResponse<User> response = iUserService.login(username,password);

        if(response.isSuccess()) {
            String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(response.getData()), null);
            Cookie cookie = new Cookie("Authorization", jwt);
            resp.addCookie(cookie);
        }

        return response;
    }
}
